<?php

App::uses('Component', 'Controller');

/**
 * Description of AccountEmailComponent
 *
 * @author Francis Adu-Gyamfi <francis.adu-gyamfi@matrixdesigns.org>
 */
class AccountEmailComponent extends Component {

    public $components = array('Email');
    public $controller = null;
    
    public function initialize(Controller $controller) {
        parent::initialize($controller);
        
        $this->controller = $controller;
    }
    
    private function checkAddressFormat($addresses) {
        if (is_string($addresses)) {
            $addresses = explode(",", $addresses);
        }

        $formatted = array();
        if (is_array($addresses)) {
            foreach ($addresses as $address) {
                if (strpos($address, "<") >= 0 && strpos($address, ">") >= 0 ) {
                    $formatted[] = $address;
                } else {
                    $formatted[] = "$address <$address>";
                }
            }
        }

        return $formatted;
    }

    private function setEmailParameters($ps = array()) {

        $default = array(
            'from' => 'Memberz Support <support@memberz.org>',
            'to' => array('Member <example@memberz.org>'),
            'cc' => array(),
            'bcc' => array(),
            'subject' => 'Sample Email Subject',
            'replyTo' => 'Memberz Support <no-reply@memberz.org>',
            'message' => ''
        );

        $params = array_merge($default, $ps);

        $this->Email->to = $this->checkAddressFormat($params['to']);
        $this->Email->cc = $this->checkAddressFormat($params['cc']);
        $this->Email->bcc = $this->checkAddressFormat($params['bcc']);
        $this->Email->subject = $params['subject'];
        $this->Email->replyTo = $params['replyTo'];
        $this->Email->from = $params['from'];

        //Send as 'html', 'text' or 'both' (default is 'text')
        $this->Email->sendAs = 'html'; // because we like to send pretty mail
        $this->Email->template = isset($params['template']) ? $params['template'] : "empty_message";
        $this->Email->delivery = 'smtp';
        
        $this->controller->set('message', $params['message']);
        
        if( $params ) {
            $this->controller->set($params['variables']);
        }
    }

    /**
     * Sends an email to the specified email on the specified member account
     * 
     * @param type $member_account_id
     * @return type
     */
    public function emailMemberAccountActivation($member_account_id, $source = 'website') {
        $account = ClassRegistry::init('MemberAccount')->find('first', array(
            'contain' => array('Member'),
            'conditions' => array(
                'MemberAccount.id' => $member_account_id
            )
        ));

        if ($account) {
            $this->setEmailParameters(array(
                'to' => "{$account['Member']['first_name']} {$account['Member']['last_name']} <{$account['MemberAccount']['username']}>",
                'subject' => "Memberz Account Activation",
                'template' => 'members/account_activation',
                'variables' => array(
                    'account' => $account,
                    'source' => $source
                )
            ));

            if ($this->Email->send()) {
                return array('status' => 'success', 'message' => 'Account Activation Email Sent Successfully');
            }
        }

        return array('status' => 'failed', 'message' => 'Failed to send account activation email');
    }
    
    /**
     * Sends an email to the specified email on the specified member account
     * 
     * @param type $member_account_id
     * @return type
     */
    public function emailOrganisationAccountActivation($organisation_account_id, $source = 'website') {
        $account = ClassRegistry::init('OrganisationAccount')->find('first', array(
            'contain' => array(
                'MemberAccount' => array(
                    'Member' => array(
                        'fields' => array('title', 'full_name', 'first_name', 'last_name', 'middle_name')
                    )
                ),
                'Organisation', 'OrganisationRole'
            ),
            'conditions' => array(
                'OrganisationAccount.id' => $organisation_account_id
            )
        ));

        if ($account) {
            $this->setEmailParameters(array(
                'to' => "{$account['MemberAccount']['Member']['first_name']} {$account['MemberAccount']['Member']['last_name']} <{$account['MemberAccount']['username']}>",
                'subject' => "Memberz Organisation Account Activation",
                'template' => 'organisation/account_activation',
                'variables' => array(
                    'account' => $account,
                    'source' => $source
                )
            ));

            if ($this->Email->send()) {
                return array('status' => 'success', 'message' => 'Account Activation Email Sent Successfully');
            }
        }

        return array('status' => 'failed', 'message' => 'Failed to send account activation email');
    }
    
    /**
     * Sends an email to the specified email on the specified organisation account
     * 
     * @param type $organisation_id
     * @return type
     */
    public function emailOrganisationActivation($organisation_account_id, $source = 'website') {
        $account = ClassRegistry::init('OrganisationAccount')->find('first', array(
            'contain' => array('Organisation', 'MemberAccount' => array('Member')),
            'conditions' => array(
                'OrganisationAccount.id' => $organisation_account_id
            )
        ));

        if ($account) {
            $this->setEmailParameters(array(
                'to' => "{$account['MemberAccount']['Member']['first_name']} {$account['MemberAccount']['Member']['last_name']} <{$account['MemberAccount']['username']}>",
                'subject' => "Organisation Account Activation",
                'template' => 'organisation/account_activation',
                'variables' => array(
                    'account' => $account,
                    'source' => $source
                )
            ));

            try {
                if ($this->Email->send()) {
                    $this->setEmailParameters(array(
                        'to' => "support@memberz.org",
                        'subject' => "New Organisation Registered",
                        'template' => 'organisation/account_registration',
                        'variables' => array(
                            'account' => $account,
                            'source' => $source
                        )
                    ));
                    
                    $this->Email->send();
                    
                    return array('status' => 'success', 'message' => 'Account Activation Email Sent Successfully');
                }
                
            } catch (Exception $e) {
                return array('status' => 'failed', 'message' => 'Failed to send account activation email');
            }
        }

        return array('status' => 'failed', 'message' => 'Failed to send account activation email');
    }
    
    /**
     * Sends an email to the specified email on the specified organisation account
     * 
     * @param type $organisation_id
     * @return type
     */
    public function emailOrganisationDeactivation($organisation_id, $source = 'website') {
        $accounts = ClassRegistry::init('OrganisationAccount')->find('all', array(
            'contain' => array('OrganisationRole', 'Organisation', 'MemberAccount' => array('Member')),
            'conditions' => array(
                'OrganisationAccount.organisation_id' => $organisation_id,
                'OrganisationRole.admin_access' => 1
            )
        ));
        
        $sent = 0;

        if ($accounts) {
            
            foreach($accounts as $account) {
                
                $this->setEmailParameters(array(
                    'to' => "{$account['MemberAccount']['Member']['first_name']} {$account['MemberAccount']['Member']['last_name']} <{$account['MemberAccount']['username']}>",
                    'subject' => "Organisation Deletion Requested",
                    'template' => 'organisation/deletion_request',
                    'variables' => array(
                        'account' => $account,
                        'source' => $source
                    )
                ));

                try {
                    if ($this->Email->send()) {
                        $sent++;
                    }

                } catch (Exception $e) {
                    return array('status' => 'failed', 'message' => 'Failed to send account activation email');
                }
            }
        }
        
        if( $sent ) {
            $this->setEmailParameters(array(
                'to' => "support@memberz.org",
                'subject' => "Organisation Deletion Requested",
                'template' => 'organisation/deletion_request',
                'variables' => array(
                    'account' => $account,
                    'source' => $source
                )
            ));

            $this->Email->send();

            return array('status' => 'success', 'message' => 'Account Activation Email Sent Successfully');
        }

        return array('status' => 'failed', 'message' => 'Failed to send account activation email');
    }
    
    /**
     * Sends a password reset email to the username specified
     * 
     * @param string $username
     * @return array
     */
    public function emailPasswordReset($username) {
        $data = ClassRegistry::init('MemberAccount')->getMemberAccount($username);

        if ($data) {
            $account = $data['account'];
            
            $this->setEmailParameters(array(
                'to' => "{$account['Member']['first_name']} {$account['Member']['last_name']} <{$account['MemberAccount']['username']}>",
                'subject' => "Account Password Reset",
                'template' => 'members/password_reset',
                'variables' => array(
                    'first_name' => $account['Member']['first_name'],
                    'last_name' => $account['Member']['last_name'],
                    'username' => $username,
                    'check_hash' => $data['check_hash']
                )
            ));

            try {
                if ($this->Email->send()) {
                    return array('status' => 'success', 'message' => 'Password Reset Email Sent Successfully');
                }
            } catch (Exception $e) {
                return array('status' => 'failed', 'message' => 'Failed to send password reset email');
            }
        }

        return array('status' => 'failed', 'message' => 'An account was not found for the username provided. Please try again');
    }
    
    /**
     * Sends a password reset email to the username specified
     * 
     * @param int $account_id
     * @return array
     */
    public function emailPasswordChangeNotification($account_id) {
        $account = ClassRegistry::init('MemberAccount')->find('first', array(
            'contain' => array('Member'),
            'conditions' => array(
                'MemberAccount.id' => $account_id,
                'MemberAccount.active' => 1
            )
        ));

        if ($account) {
            $this->setEmailParameters(array(
                'to' => "{$account['Member']['first_name']} {$account['Member']['last_name']} <{$account['MemberAccount']['username']}>",
                'subject' => "Account Password Changed",
                'template' => 'members/password_changed',
                'variables' => array(
                    'account' => $account
                )
            ));

            try {
                if ($this->Email->send()) {
                    return array('status' => 'success', 'message' => 'Password Change Notification Email Sent Successfully');
                }
            } catch (Exception $e) {
                return array('status' => 'failed', 'message' => 'Failed to send password change notification email.');
            }
        }

        return array('status' => 'failed', 'message' => 'An account was not found for the username provided. Please try again');
    }

}
